package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.MQConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.LoginUserVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enums.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 结算页数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() {
        LoginUserVo userVo = LoginUserInterceptor.threadLocal.get();
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //获取主线程的请求上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        //1.异步远程查询所有收获地址列表
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //异步开启新的线程，会丢失请求上下文信息，这里需要将主线程的请求放到新线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(userVo.getId());
            orderConfirmVo.setAddress(address);
        }, executor);


        //2.远程查询购物车所有选中的购物项，并重新计算价格，购物车内的价格可能已发生变化
        CompletableFuture<Void> itemsFuture = CompletableFuture.runAsync(() -> {
            //异步开启新的线程，会丢失请求上下文信息，这里需要将主线程的请求放到新线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();

            //远程查询库存
            List<Long> skuIds = userCartItems.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wareFeignService.getSkusHasStock(skuIds);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                for (OrderItemVo itemVo : userCartItems) {
                    itemVo.setHasStock(map.get(itemVo.getSkuId()));
                }
            }
            orderConfirmVo.setItems(userCartItems);
        }, executor);


        //3.远程查询优惠券信息，这里只查询用户积分
        Integer integration = userVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //todo 4.计算运费，这里默认给10，不计算了
        orderConfirmVo.setFare(new BigDecimal(10));

        //5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + userVo.getId(), token, 30, TimeUnit.MINUTES);

        try {
            CompletableFuture.allOf(addressFuture, itemsFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return orderConfirmVo;
    }

    /**
     * 提交订单
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public SubmitOrderResponseVo sumbitOrder(OrderSumbitVo vo) {
        LoginUserVo userVo = LoginUserInterceptor.threadLocal.get();
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();

        //验证令牌【令牌的对比和删除要保证原子性】
        //该脚本会返回0和1
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + userVo.getId()), orderToken);
        if (result == 1) { //验证成功

            //1.创建订单相关信息
            OrderCreateTo order = createOrder(vo);
            //2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount(); //订单计算的金额
            BigDecimal payPrice = vo.getPayPrice();  //前端传过来的金额
            //对比金额，因为前端传过来的和后端计算出来的小数位数可能不一样，所以不能用相等去判断
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {

                //3.保存订单
                saveOrder(order);

                //4.锁定库存，只要有异常就回滚订单数据
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setTitle(item.getSkuName());
                    itemVo.setCount(item.getSkuQuantity());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);

                /*
                 * 远程锁库存，不做分布式事务处理的话有可能会库存锁定成功了，订单却回滚了【库存锁定成功后超时或者报错导致库存没回滚，订单却回滚】
                 * 为了保证高并发，不建议使用seata事务。需要在订单回滚后让库存自动回滚。
                 */
                R r = wareFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //库存锁定成功
                    responseVo.setOrder(order.getOrder());

                    //订单创建成功，给mq发送消息
                    rabbitTemplate.convertAndSend(MQConstant.ORDER_EVENT_EXCHANGE, MQConstant.ORDER_CTEATE_ORDER_KEY, order.getOrder());

                } else {
                    //库存锁定失败
                    responseVo.setCode(3);
                    throw new RRException(BizCodeEnum.WARE_NO_STOCK_EXCEPTION);
                }
            } else {
                //金额对比失败,前端传过来的金额和后端计算的金额相差超过0.01元
                responseVo.setCode(2);
                throw new RRException(BizCodeEnum.ORDER_SUBMIT_PRICE_EXCEPTION);
            }


        } else {
            //令牌验证失败
            responseVo.setCode(1);
            throw new RRException(BizCodeEnum.ORDER_SUBMIT_REPEAT_EXCEPTION);
        }
        return responseVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /**
     * 关闭订单
     *
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity!=null && orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            updateEntity.setId(entity.getId());
            this.updateById(updateEntity);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //关单成功给解锁库存队列发送消息
            rabbitTemplate.convertAndSend(MQConstant.ORDER_EVENT_EXCHANGE,MQConstant.ORDER_RELEASE_OTHER_KEY,orderTo);
        }
    }

    /**
     * 创建秒杀订单
     * @param seckillOrder
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal(seckillOrder.getNum().toString()));
        orderEntity.setPayAmount(multiply);

        this.save(orderEntity);

        //保存订单项
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrder.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(seckillOrder.getNum());
        //todo 获取当前sku的其他详细信息进行赋值
        orderItemService.save(itemEntity);

    }


    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItems.forEach(item->item.setOrderId(orderEntity.getId()));
        orderItemService.saveBatch(orderItems);
    }


    /**
     * 创建订单
     *
     * @param vo
     * @return
     */
    private OrderCreateTo createOrder(OrderSumbitVo vo) {
        OrderCreateTo createTo = new OrderCreateTo();
        //1.生成订单号
        String orderSn = IdWorker.getTimeId();
        //构建订单信息
        OrderEntity orderEntity = buildOrder(vo, orderSn);

        //2.获取所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3.计算价格
        computePrice(orderEntity, itemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    /**
     * 计算订单价格
     *
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal coupon = BigDecimal.ZERO;
        BigDecimal integration = BigDecimal.ZERO;
        BigDecimal promotion = BigDecimal.ZERO;
        Integer gift = 0;
        Integer growth = 0;
        //订单总额，每一个订单项总额的总和
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration.add(entity.getIntegrationAmount());
            promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift += entity.getGiftIntegration();
            growth += entity.getGiftGrowth();
        }
        //订单总额
        orderEntity.setTotalAmount(total);
        //应付总额（订单总额+运费）
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);

        //设置积分
        orderEntity.setIntegration(gift);
        orderEntity.setGrowth(growth);
    }

    /**
     * 构建订单信息
     *
     * @param vo
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(OrderSumbitVo vo, String orderSn) {
        LoginUserVo userVo = LoginUserInterceptor.threadLocal.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(userVo.getId());
        entity.setPayType(vo.getPayType());
        //todo 计算运费，这里默认10元，不计算了
        entity.setFreightAmount(new BigDecimal(10));
        //获取收获地址
        R addressInfo = memberFeignService.info(vo.getAddressId());
        if (addressInfo.getCode() != 0)
            throw new RRException(BizCodeEnum.USER_ADDRESS_INVAILD_EXCEPTION);

        AddressVo address = addressInfo.getData("memberReceiveAddress", new TypeReference<AddressVo>() {
        });
        entity.setReceiverProvince(address.getProvince());
        entity.setReceiverCity(address.getCity());
        entity.setReceiverRegion(address.getRegion());
        entity.setReceiverDetailAddress(address.getDetailAddress());
        entity.setReceiverName(address.getName());
        entity.setReceiverPhone(address.getPhone());
        entity.setReceiverPostCode(address.getPostCode());

        //设置订单状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setDeleteStatus(0);
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
        if (CollectionUtils.isEmpty(userCartItems))
            throw new RRException(BizCodeEnum.CART_CARTITEM_NOT_EXISTS_EXCEPTION);
        List<OrderItemEntity> itemEntities = userCartItems.stream().map(cartItem -> {
            //构建订单项
            OrderItemEntity itemEntity = buildOrderItem(cartItem);
            itemEntity.setOrderSn(orderSn);
            return itemEntity;
        }).collect(Collectors.toList());
        return itemEntities;
    }

    /**
     * 构建每一个订单项数据
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();

        //1.订单信息

        //2.spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        if (data == null) {
            throw new RRException(BizCodeEnum.PRODUCT_SPU_NULL_EXCEPTION);
        }
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

        //3.sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());

        //4.todo 优惠信息,略过

        //5.积分信息,积分的值等于价格的int值
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6.订单项的价格
        itemEntity.setPromotionAmount(BigDecimal.ZERO);
        itemEntity.setCouponAmount(BigDecimal.ZERO);
        itemEntity.setIntegrationAmount(BigDecimal.ZERO);
        //当前订单项的实际金额，总额减去各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(BigDecimal.valueOf(itemEntity.getSkuQuantity()));
        BigDecimal real = orign.subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(real);
        return itemEntity;
    }
}